package me.fung.rem.app.main

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import me.fung.keen.app.view.View
import me.fung.rem.app.GlobalState
import me.fung.rem.app.content.PAGE_REM_CONTENT
import me.fung.rem.app.auth.SignUpView
import me.fung.rem.app.navigation
import me.fung.rem.app.auth.SignInView
import me.fung.rem.app.common.loading

private var enableFirstAutoSignIn = true

class MainView : View<MainPresenter>() {

    @Composable
    override fun content(modifier: Modifier) {
        val state = remember { GlobalState }
        var loading by remember { mutableStateOf(true) }

        LaunchedEffect(Unit) {
            p.loadConfig()
            if (enableFirstAutoSignIn) {
                p.autoSign()
                enableFirstAutoSignIn = false
            }
            loading = false
        }
        Box(modifier, contentAlignment = Alignment.Center) {
            if (loading) {
                loading(Modifier.align(Alignment.Center))
            } else if (!state.hasKey) {
                SignUpView().content(Modifier.fillMaxSize())
            } else if (state.authorized) {
                navigation.goto(PAGE_REM_CONTENT)
            } else {
                // 显示授权界面
                SignInView().show(Modifier.fillMaxSize())
            }
        }
    }
}
